package jobs;

public class ProductTest {
    public static void main(String[] args) throws CloneNotSupportedException {
        // 创建原始商品
        Product original = new Product("手机", 3999.0, 100);
        // 克隆两个新商品
        Product clone1 = (Product) original.clone();
        Product clone2 = (Product) original.clone();

        // 验证属性一致
        System.out.println("clone1.equals original: " + original.equals(clone1));
        System.out.println("clone2.equals original: " + original.equals(clone2));
        // 验证不是同一实例
        System.out.println("clone1 == original: " + (clone1 == original));
        System.out.println("clone2 == original: " + (clone2 == original));
    }
}

// 原型模式实现Product类
class Product implements Cloneable {
    private String name;
    private double price;
    private int stock;

    public Product(String name, double price, int stock) {
        this.name = name;
        this.price = price;
        this.stock = stock;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }

    public int getStock() {
        return stock;
    }

    // 重写clone方法，支持克隆
    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    // 重写equals方法，便于属性一致性验证
    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Product product = (Product) obj;
        return Double.compare(product.price, price) == 0 &&
                stock == product.stock &&
                name.equals(product.name);
    }

    @Override
    public int hashCode() {
        int result = name.hashCode();
        long temp = Double.doubleToLongBits(price);
        result = 31 * result + (int) (temp ^ (temp >>> 32));
        result = 31 * result + stock;
        return result;
    }
}